package city.spring.modules.medicine.controller;

import city.spring.modules.medicalstation.drugwarehouse.service.DrugwarehouseService;
import city.spring.modules.medicine.entity.MedicinedeliveryMedicineExtEntity;
import city.spring.modules.medicine.repository.MedicinedeliveryMedicineExtRepository;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.medicine.service.MedicinedeliveryMedicineExtService;
import city.spring.modules.medicine.service.MedicinedeliveryService;
import city.spring.modules.medicine.service.MedicinereceiptService;
import city.spring.modules.medicine.vo.MedicinedeliveryMedicineVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：药品出库与药品关联表
 *
 * @author 谢金婷
 * @date 2020-07-08 16:17:05
 */
@RestController
@RequestMapping("/medicinedelivery/{deliveryId}/medicine")
public class MedicinedeliveryMedicineExtController extends ApiController {
    private final MedicinedeliveryMedicineExtService medicinedeliveryMedicineExtService;
    private final MedicinedeliveryMedicineExtRepository deliveryMedicineExtRepository;
    private final MedicineService medicineService;
    private final DrugwarehouseService drugwarehouseService;
    private final MedicinedeliveryService medicinedeliveryService;
    private final MedicinereceiptService medicinereceiptService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicinedeliveryMedicineExtEntity, ?>> entityOrderFields;

    public MedicinedeliveryMedicineExtController(MedicinedeliveryMedicineExtService medicinedeliveryMedicineExtService, MedicinedeliveryMedicineExtRepository deliveryMedicineExtRepository, MedicineService medicineService, DrugwarehouseService drugwarehouseService, MedicinedeliveryService medicinedeliveryService, MedicinereceiptService medicinereceiptService) {
        this.medicinedeliveryMedicineExtService = medicinedeliveryMedicineExtService;
        this.deliveryMedicineExtRepository = deliveryMedicineExtRepository;
        this.medicineService = medicineService;
        this.drugwarehouseService = drugwarehouseService;
        this.medicinedeliveryService = medicinedeliveryService;
        this.medicinereceiptService = medicinereceiptService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicinedeliveryMedicineExtEntity::getId);
        entityOrderFields.add(MedicinedeliveryMedicineExtEntity::getMedicinedeliveryId);
        entityOrderFields.add(MedicinedeliveryMedicineExtEntity::getMedicineId);
        entityOrderFields.add(MedicinedeliveryMedicineExtEntity::getDeliveryquantity);
        entityOrderFields.add(MedicinedeliveryMedicineExtEntity::getTotal);
    }

    @ModelAttribute
    public void getDeliveryId(@PathVariable Integer deliveryId) {
        if (deliveryId == null) {
            throw new RuntimeException("出库单ID必须不为空");
        }
        System.out.println("deliveryId" + deliveryId);
    }

    /**
     * 获取全部的 <strong>药品出库与药品关联表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MedicinedeliveryMedicineExtEntity entity) {
        LambdaQueryChainWrapper<MedicinedeliveryMedicineExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>药品出库与药品关联表</strong> 列表
     *
     * @param pageable 分页参数信息
     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, MedicinedeliveryMedicineExtEntity entity) {
//        LambdaQueryChainWrapper<MedicinedeliveryMedicineExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicinedeliveryMedicineExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }

    /**
     * 获取药品出库所有药品列表
     *
     * @param deliveryId 出库单id
     */
    @GetMapping
    public Object list(@PathVariable Integer deliveryId) {
        return success(deliveryMedicineExtRepository.getDeliveryMedicines(deliveryId));
    }

    /**
     * 获取一个 <strong>药品出库与药品关联表</strong>
     *
     * @param extId 主键ID
     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(medicinedeliveryMedicineExtService.getById(id));
//    }
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable Integer deliveryId, @PathVariable Integer extId) {
        return success(deliveryMedicineExtRepository.getDeliveryMedicine(deliveryId, extId));
    }


    /**
     * 添加一个 <strong>药品出库与药品关联表</strong>
     *
     * @param entity 修改后的信息
     */
//    @PostMapping
//    public Object add(@RequestBody MedicinedeliveryMedicineExtEntity entity) {
//        medicinedeliveryMedicineExtService.saveMedicinedeliveryMedicineExt(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }

    /**
     * 给出库单添加多个药品信息
     *
     * @param deliveryId 出库单ID
     * @param medicines  所添加的药品信息列表
     * @return
     */
    @PostMapping
    public Object addAll(@PathVariable Integer deliveryId, @RequestBody List<MedicinedeliveryMedicineExtEntity> medicines) {
        // 查出已有的数据
        List<MedicinedeliveryMedicineVO> dbMedicines = deliveryMedicineExtRepository.getDeliveryMedicines(deliveryId);

        // 数据库已经存在的药品列表
        Set<Integer> dbMedicineIdsSet = dbMedicines.stream()
                .map(MedicinedeliveryMedicineExtEntity::getMedicineId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<MedicinedeliveryMedicineExtEntity> needSavemedicines = medicines.stream()
                .filter(item -> {
                    item.setMedicinedeliveryId(deliveryId);
                    Integer medicineId = item.getMedicineId();
                    // 过滤出不存在数据库中的数据
                    return medicineId != null && !dbMedicineIdsSet.contains(medicineId);
                }).collect(Collectors.toList());

        if (!needSavemedicines.isEmpty()) {
            medicinedeliveryMedicineExtService.saveBatch(needSavemedicines);
        }
//
//        System.out.println("needSavemedicines" + needSavemedicines);
//        BigDecimal totalquantity = new BigDecimal(0);
//        for (MedicinedeliveryMedicineExtEntity ms : needSavemedicines) {
//            totalquantity = totalquantity.add(ms.getDeliveryquantity());
//
//        }
//        System.out.println("totalquantity:" + totalquantity);
//
//        // 领用单领用数量
////        MedicinedeliveryEntity medicinedeliveryEntity = medicinedeliveryService.getById(deliveryId);
//        MedicinereceiptEntity medicinereceiptEntity = medicinereceiptService.getById(medicinedeliveryService.getById(deliveryId).getMedicinereceiptId());
//        if (!needSavemedicines.isEmpty() && totalquantity.compareTo(medicinereceiptEntity.getQuantity()) == 0) {
//            medicinedeliveryMedicineExtService.saveBatch(needSavemedicines);
//
//            // 根据出库单id查找关联的药品MedicinedeliveryMedicineExtEntity
//            List<MedicinedeliveryMedicineExtEntity> medicineExtEntities = deliveryMedicineExtRepository.getDeliveryMts(deliveryId);
//            for (MedicinedeliveryMedicineExtEntity medicineExtEntity : medicineExtEntities) {
//                /**
//                 * 根据MedicinedeliveryMedicineExtEntity的药品id查找药品信息
//                 */
//                MedicineEntity medicineEntity = medicineService.getById(medicineExtEntity.getMedicineId());
//
//                //判断单个药品出库数量不能大于其库存数量（没实现）
//                // 获取关联MedicinedeliveryMedicineExtEntity的入库数量
//                BigDecimal deliveryquantity = medicineExtEntity.getDeliveryquantity() == null ? BigDecimal.ZERO : medicineExtEntity.getDeliveryquantity();
//                BigDecimal standard = medicineExtEntity.getStandard() == null ? BigDecimal.ZERO : medicineExtEntity.getStandard();
//                // 1.获取药品库存
//                BigDecimal quantity = medicineEntity.getQuantity() == null ? BigDecimal.ZERO : medicineEntity.getQuantity();
//                System.out.println("quantity" + quantity);
//                /**
//                 * 关联药品的更新 MedicinedeliveryMedicineExtEntity
//                 */
//                //获取药品价格
//                BigDecimal unitprice = medicineEntity.getUnitprice() == null ? BigDecimal.ZERO : medicineEntity.getUnitprice();
//                //计算 MedicinedeliveryMedicineExtEntity 总价
//                medicineExtEntity.setTotal(deliveryquantity.multiply(unitprice));
//                medicineExtEntity.setQuantitySpecifications(deliveryquantity.multiply(standard));
//
//                // 更新 MedicinedeliveryMedicineExtEntity
//                medicinedeliveryMedicineExtService.updateMedicinedeliveryMedicineExt(medicineExtEntity);
//
//                /**
//                 * 出库后更新药品库存
//                 */
//                //更新出库数量=原来的出库数量+现在的出库数量
////            BigDecimal mdeliveryquantity = medicineEntity.getDeliveryquantity() == null ? BigDecimal.ZERO : medicineEntity.getDeliveryquantity();
////            medicineEntity.setDeliveryquantity(mdeliveryquantity.add(deliveryquantity));
////            System.out.println(mdeliveryquantity + "====" + deliveryquantity);
////            // 更新库存=原来的库存-现在的出库数量
////            BigDecimal mquantity = medicineEntity.getQuantity() == null ? BigDecimal.ZERO : medicineEntity.getQuantity();
////            medicineEntity.setQuantity(mquantity.subtract(deliveryquantity));
////            System.out.println(mquantity + "----=" + deliveryquantity);
////            medicineService.updateMedicine(medicineEntity);
//
//                MedicinedeliveryVO medicinedelivery = medicinedeliveryService.getMedicinedeliveryById(String.valueOf(deliveryId));
//                // 新增医护站入库记录 每一种药品对应一条入库记录
//                DrugwarehouseEntity drugwarehouseEntity = new DrugwarehouseEntity();
//                drugwarehouseEntity.setDeliveryId(medicineExtEntity.getMedicinedeliveryId());
//                // 出库药品货架编号
//                MedicineEntity medicineEntity1 = medicineService.getById(medicineExtEntity.getMedicineId());
//                drugwarehouseEntity.setDeliveryShelflevelId(medicineEntity1.getShelfId());
//                drugwarehouseEntity.setStorehouseId(medicinedelivery.getWstorehouseId());
//                drugwarehouseEntity.setMedicineId(medicineExtEntity.getMedicineId());
//                drugwarehouseEntity.setMedicineCode(medicineExtEntity.getMedicineCode());
//                drugwarehouseEntity.setQuantity(medicineExtEntity.getDeliveryquantity());
//                drugwarehouseEntity.setUnit(medicineExtEntity.getUnit());
//                drugwarehouseEntity.setQuantitySpecifications(medicineExtEntity.getQuantitySpecifications());
//                drugwarehouseEntity.setSpecifications(medicineExtEntity.getSpecifications());
//                drugwarehouseEntity.setUnitprice(medicineExtEntity.getUnitprice());
//                drugwarehouseEntity.setIswarehouse(2);
//                drugwarehouseEntity.setApprovalStatus(1);
//                drugwarehouseEntity.setWarehousingmethod(medicinedelivery.getDestination());
//                drugwarehouseService.saveDrugwarehouse(drugwarehouseEntity);
//            }
//        } else {
//            // 出库数量不等于领用申请数量 不能生成出库单
//            // 修改出库状态为未出库
//            medicinereceiptEntity.setDeliveryStatus(2);
//            medicinereceiptService.lambdaUpdate()
//                    .set(MedicinereceiptEntity::getDeliveryStatus, medicinereceiptEntity.getDeliveryStatus())
//                    .eq(MedicinereceiptEntity::getId, medicinereceiptEntity.getId())
//                    .update();
//            // 删除生成的出库单
//            medicinedeliveryService.deleteMedicinedelivery(String.valueOf(medicinedeliveryService.getById(deliveryId).getId()));
//            // 窗口提示
//            JOptionPane.showMessageDialog(null, "出库数量不等于领用申请数量", "错误", JOptionPane.ERROR_MESSAGE);
////            throw new RuntimeException("出库数量不等于领用申请数量");
//        }

        return success(null);
    }

    /**
     * 修改一个 <strong>药品出库与药品关联表</strong>
     *
     * @param deliveryId 出库单ID
     * @param extId      关联ID
     * @param extEntity  修改后的信息
     */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody MedicinedeliveryMedicineExtEntity entity) {
//        entity.setId(id);
//        medicinedeliveryMedicineExtService.updateMedicinedeliveryMedicineExt(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }
    @PutMapping("{extId}")
    public Object update(@PathVariable Integer deliveryId, @PathVariable Integer extId, @RequestBody MedicinedeliveryMedicineExtEntity extEntity) {
        extEntity.setId(String.valueOf(extId));
        extEntity.setMedicinedeliveryId(deliveryId);
        medicinedeliveryMedicineExtService.updateMedicinedeliveryMedicineExt(extEntity);
        return success(null);
    }

    /**
     * 删除一个 <strong>药品出库与药品关联表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicinedeliveryMedicineExtService.deleteMedicinedeliveryMedicineExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品出库与药品关联表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicinedeliveryMedicineExtService.deleteMedicinedeliveryMedicineExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicinedeliveryMedicineExtEntity> buildLambdaQuery(MedicinedeliveryMedicineExtEntity entity) {
        LambdaQueryChainWrapper<MedicinedeliveryMedicineExtEntity> lambdaQuery = medicinedeliveryMedicineExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MedicinedeliveryMedicineExtEntity::getId, entity.getId());
        lambdaQuery.eq(entity.getMedicinedeliveryId() != null, MedicinedeliveryMedicineExtEntity::getMedicinedeliveryId, entity.getMedicinedeliveryId());
        lambdaQuery.eq(entity.getMedicineId() != null, MedicinedeliveryMedicineExtEntity::getMedicineId, entity.getMedicineId());
        lambdaQuery.eq(entity.getDeliveryquantity() != null, MedicinedeliveryMedicineExtEntity::getDeliveryquantity, entity.getDeliveryquantity());
        lambdaQuery.eq(entity.getTotal() != null, MedicinedeliveryMedicineExtEntity::getTotal, entity.getTotal());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicinedeliveryMedicineExtEntity> buildQuery(MedicinedeliveryMedicineExtEntity entity) {
        QueryWrapper<MedicinedeliveryMedicineExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.eq(entity.getMedicinedeliveryId() != null, "medicinedelivery_id", entity.getMedicinedeliveryId());
        wrapper.eq(entity.getMedicineId() != null, "medicine_id", entity.getMedicineId());
        wrapper.eq(entity.getDeliveryquantity() != null, "deliveryquantity", entity.getDeliveryquantity());
        wrapper.eq(entity.getTotal() != null, "total", entity.getTotal());
        return wrapper;
    }

}
